<template>
  <el-card class="box-card" shadow="never">
    <!-- <template #header>
      <div>
        <span>生成自定义报表</span>
      </div>
    </template> -->
    <div class="w-full sm:w-[40%] mx-auto">
      <el-form :model="gen" ref="form" label-width="100px">
        <el-form-item
          label="视图名称"
          prop="table_name"
          :rules="[
            {
              required: true,
              message: '视图名称不能为空',
            },
          ]"
        >
          <el-input v-model="gen.table_name" clearable placeholder="输入对应视图获取对应字段" @keydown.enter="controllerBlur" width="200" />
        </el-form-item>
        <el-form-item
          label="报表名称"
          prop="report_name"
          :rules="[
            {
              required: true,
              message: '报表名称不能为空',
            },
          ]"
        >
          <el-input v-model="gen.report_name" clearable placeholder="请输入自定义报表名称" @keydown.enter="controllerBlur" width="200" />
        </el-form-item>
      </el-form>
    </div>
    <Structure :customcolumn="customcolumn" v-loading="selfLoading" />
    <div class="w-full flex justify-center pt-5">
      <el-button type="primary" @click="submitGenerate(form)" class="ml-5">{{ $t('system.finish') }}</el-button>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { useCreate } from '/admin/composables/curd/useCreate'
import { useShow } from '/admin/composables/curd/useShow'
import { useGenerateStore } from './store'
import { onMounted, reactive, ref, watch, defineProps } from 'vue'
import Structure from './structure.vue'
import http from '/admin/support/http'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['close'])

const props = defineProps({
  primary: String | Number,
  api: String,
  supplierId: Number,
  title: String,
  tableData: Object,
})

const { formData, loading, submitForm, close } = useCreate(props.api, props.primary)
const generateStore = useGenerateStore()

let gen = reactive({})
if (props.primary) {
  useShow(props.api, props.primary, formData)
  gen = formData
} else {
  gen = generateStore.getCodeGen
}

console.log(props.primary)
console.log(props.tableData)

// const schemaId = router.currentRoute.value.params.schema
const schemaId = 1

onMounted(() => {
  if (!generateStore.getSchemaId) {
    generateStore.setSchemaId(schemaId)
    getSchema()
  } else {
    if (schemaId !== generateStore.getSchemaId) {
      generateStore.setSchemaId(schemaId)
      generateStore.resetStructures()
      getSchema()
    }
  }
})

let defaultField = ref([])

const getSchema = () => {
  http.get('schema/' + schemaId).then(r => {
    console.log(r.data.data)
    gen.module = r.data.data.module
    gen.schema = r.data.data.name
    gen.model = r.data.data.name.replace(/\_(\w)/g, (value, letter) => {
      return letter.toUpperCase()
    })
    console.log('获取默认字段：', r.data.data.columns)
    defaultField.value = r.data.data.columns
    // generateStore.initStructures(r.data.data.columns)
    // generateStore.initStructures(customcolumn.value)
  })
}

const customcolumn = ref([])
const customTable_name = ref('')
const selfLoading = ref(false)

const controllerBlur = e => {
  selfLoading.value = true
  console.log('控制器拿到的数据', gen.table_name)
  http.get(`customReport/show/table/${gen.table_name}`).then(r => {
    console.log('获取column', r.data)
    selfLoading.value = false
    if (r.data.code == 10000) {
      ElMessage.success(r.data.message)
      // customcolumn.value = r.data.data.column
      let columns = r.data.data.column
      // customTable_name.value = r.data.data.table_name
      console.log(columns)

      defaultField.value.forEach((obj, index) => {
        obj.name = columns[index]
        obj.label = columns[index]
        obj.default = columns[index]
      })
      console.log(defaultField.value)

      defaultField.value.length = columns.length
      generateStore.initStructures(defaultField.value)
    }
  })
}

const form = ref<FormInstance>()
const submitGenerate = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      console.log('提交表格', generateStore.$state)
      let fields_json = generateStore.$state.structures.map(item => {
        return {
          column: item.field,
          label: item.label,
          is_show: item.list,
          is_query: item.search,
          query_compont: item.form_component,
          condition: item.search_op,
        }
      })
      console.log(fields_json)
      let sendObj = {
        table_name: gen.table_name,
        report_name: gen.report_name,
        fields_json: fields_json,
      }
      console.log('生成的提交数据', sendObj)

      http.post('customReport/manage', sendObj).then(r => {
        ElMessage.success(r.data.message)
        emit('close')
      })
    } else {
      return false
    }
  })
}
</script>

<style lang="css">
.el-form-item {
  width: 450px;
}
</style>
